<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth as com_auth;
use think\Validate;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {

                return $this->selectpage();
            }
            $where = array();
            if($this->otype == 'daili'){
                //省
                if($this->admin['server_type'] == 1){
                    $where[] = ['province' ,'=', $this->admin['province']];
                //市
                }elseif($this->admin['server_type'] == 2){
                    $where[] = ['city' ,'=', $this->admin['city']];
                //区
                }elseif($this->admin['server_type'] == 3){
                    $where[] = ['area' ,'=', $this->admin['area']];
                }else{
                    exit;
                }


            }



            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,$where);
            $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->order('createtime desc')
                    ->select();

            foreach ($list as $k => $v)
            {
                $v->hidden(['password', 'salt']);
                $v->parent_agent_name = $this->model->where('id',$v->parent_id)->value('nickname');
                $v->province = get_areaname($v->province);
                $v->city = get_areaname($v->city);
                $v->area = get_areaname($v->area);
                $v->regione = get_areaname($v->regione);

                $list[$k] = $v;

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 新增
     */
    public function add()
    {


        if($this->otype == 'daili') {
            $servers = [
                '0'=>'前端用户',
            ];
        }else{
            $servers = [
                '0'=>'前端用户',
                '1'=>'省服务商',
                '2'=>'市服务商',
                '3'=>'区服务商',
                '5'=>'大区服务商'
            ];
        }

        $this->assign('serverList',build_select('row[server_type]',$servers,'',['class' => 'form-control server_type']));


        if ($this->request->isPost()) {
            $data = $this->request->post("row/a");


            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'require|regex:/^1\d{10}$/',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
                'mobile.require'           => 'Mobile is incorrect',
            ];

            $validate = new Validate($rule, $msg);

            $result = $validate->check($data);

            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }




            if ($data['consume_res'] > 100 ) {
                $this->error('最大消费返点为：100%');
            }
            if ($data['contribute_res'] > 100 ) {
                $this->error('最大贡献值返点为：100%');
            }






            $com_auth = new com_auth();
            $username = $data['username'];
            $password = $data['password'];
            $email = $data['email'];
            $mobile = $data['mobile'];
            $extend = $data;

            if($extend['server_type'] != 0){
                $extend['is_agent'] = $extend['is_shop'] = 0;

                //如果是服务商，判断这个区域的服务商是否存在
                $maps['server_type'] = $extend['server_type'];
                if($extend['server_type'] == 1) $maps['province'] = $extend['province'];
                if($extend['server_type'] == 2) $maps['city'] = $extend['city'];
                if($extend['server_type'] == 3) $maps['area'] = $extend['area'];
                if($extend['server_type'] == 5) $maps['regione'] = $extend['regione'];
                $isset_user = $this->model->where($maps)->find();
                if($isset_user) $this->error('此区域服务商已存在');

            }else{

            }

            unset($extend['username']);
            unset($extend['password']);
//            unset($extend['email']);
            unset($extend['mobile']);
            $code = initcode();
            if ($com_auth->register($username, $password, $code, $mobile,$extend)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $this->success();
            } else {
                $this->error($com_auth->getError());
            }
            exit;
        }

        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    if(!$row->code) $row->code = initcode();
                    if(isset($params['parent_id']) && $params['parent_id'] == $ids){
                        $this->error('所属代理不得为自己');
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    function check_user_groups($ids){
        if(!$ids) $this->error('身份id不得为空');
        if(in_array(1,$ids) && count($ids) > 1) $this->error('服务商只可以有一种身份');
        if(!in_array(1,$ids) && !in_array(4,$ids)) $this->error('至少是消费者身份');
    }

    public function statusAajax($ids){
        $user=$this->model->where(['id'=>array('eq',$ids)])->find();
        $user=$user->toArray();
        if($user['status']=='normal'){
            $status='hidden';
        }elseif($user['status']=='hidden'){
            $status='normal';
        }
        $data['status']=$status;
        $this->model->save($data,['id'=>$ids]);
        $this->success('修改成功');
    }

}
